package com.wkg.springblogdemo.common.util;

import com.wkg.springblogdemo.common.exception.BlogException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@Slf4j
public class JwtUtils {

    private static final String secretString = "nPyamD1K6A8Yc9TxD-tRliF2W89i8QJWmIh6dOAgAKA";
    private static final SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64URL.decode(secretString));
    private static final Long EXPIRE_TIME = (long) (30F * 24 * 60 * 60 * 1000);

    /**
     * 生成token
     *
     * @param map
     * @return
     */

    public static String getToken(Map<String, Object> map) {
        return Jwts.builder()
                .setClaims(map)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .signWith(key).compact();
    }


    public static Claims parseToken(String token) {
        Claims body = null;
        try {
            body = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
        } catch (Exception e) {
            log.error("token解析失败");
        }
        return body;
    }

}
